package com.xuyanze.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author ：lzy
 * @date ：2021-10-21
 * @description：
 */
//@Slf4j
public class HttpUtils {

    public static String postForm(String url, Map<String,String> paramMap, Header[] headers){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> values = new ArrayList<>();
        for (Map.Entry<String,String> item : paramMap.entrySet()){
            values.add(new BasicNameValuePair(item.getKey(),item.getValue()));
        }

        UrlEncodedFormEntity encodedFormEntity;
        CloseableHttpResponse response=null;
        try {
            encodedFormEntity = new UrlEncodedFormEntity(values,"UTF-8");
            httpPost.setEntity(encodedFormEntity);
            Optional.ofNullable(headers).ifPresent(k->httpPost.setHeaders(k));

            response = httpClient.execute(httpPost);
            Header[] responseHeaders = response.getHeaders("Set-Cookie");
            for (Header responseHeader : responseHeaders) {
                System.out.println(responseHeader.getValue());
            }
            HttpEntity entity = response.getEntity();
            if(entity != null){
                String result = EntityUtils.toString(entity,"UTF-8");
//                log.info("http response: "+result);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null)
                    response.close();

                if(httpClient != null)
                    httpClient.close();

            }catch (IOException e){
                e.printStackTrace();
            }

        }
        return null;
    }

    public static String getCookie(String url, Map<String,String> paramMap, Header[] headers){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> values = new ArrayList<>();
        for (Map.Entry<String,String> item : paramMap.entrySet()){
            values.add(new BasicNameValuePair(item.getKey(),item.getValue()));
        }

        UrlEncodedFormEntity encodedFormEntity;
        CloseableHttpResponse response=null;
        try {
            encodedFormEntity = new UrlEncodedFormEntity(values,"UTF-8");
            httpPost.setEntity(encodedFormEntity);
            Optional.ofNullable(headers).ifPresent(k->httpPost.setHeaders(k));

            response = httpClient.execute(httpPost);
            Header[] responseHeaders = response.getHeaders("Set-Cookie");
            StringBuilder cookieBuilder = new StringBuilder();
            for (Header responseHeader : responseHeaders) {
                cookieBuilder.append(responseHeader.getValue());
                cookieBuilder.append(";");
            }
            cookieBuilder.deleteCharAt(cookieBuilder.length() - 1);
            return cookieBuilder.toString();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null)
                    response.close();

                if(httpClient != null)
                    httpClient.close();

            }catch (IOException e){
                e.printStackTrace();
            }

        }
        return null;
    }


    public static String get(String url,Header[] headers){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);

        CloseableHttpResponse response=null;
        try {
            Optional.ofNullable(headers).ifPresent(k->httpGet.setHeaders(k));
            response = httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(response.getEntity(),"UTF-8");
//                log.info("http response: "+result);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null)
                    response.close();

                if(httpClient != null)
                    httpClient.close();

            }catch (IOException e){
                e.printStackTrace();
            }

        }
        return null;
    }

}
